<template>
  <div class="compression-test">
    <n-card title="图片压缩测试">
      <n-upload
        :file-list="fileList"
        @update:file-list="handleFileListChange"
        list-type="image-card"
        :max="5"
        :custom-request="customUpload"
        accept="image/*"
      >
        <div class="upload-trigger">
          <n-icon size="48">
            <AddIcon />
          </n-icon>
          <n-text>选择图片测试压缩</n-text>
        </div>
      </n-upload>

      <n-divider />

      <n-space vertical>
        <n-text strong>压缩结果:</n-text>
        <n-space>
          <n-tag type="info">总文件: {{ fileList.length }}</n-tag>
          <n-tag type="success">成功: {{ successCount }}</n-tag>
          <n-tag type="warning">失败: {{ failedCount }}</n-tag>
        </n-space>
      </n-space>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { Add as AddIcon } from '@vicons/ionicons5'
import { smartCompress, formatFileSize } from '../../utils/imageCompression'

const message = useMessage()
const fileList = ref<UploadFileInfo[]>([])

const successCount = computed(() =>
  fileList.value.filter(f => f.status === 'finished').length
)

const failedCount = computed(() =>
  fileList.value.filter(f => f.status === 'error').length
)

const handleFileListChange = (files: UploadFileInfo[]) => {
  fileList.value = files
}

const customUpload = async ({ file }: { file: UploadFileInfo }) => {
  try {
    const fileObj = file.file as File

    if (fileObj.type.startsWith('image/')) {
      console.log('压缩图片:', fileObj.name, formatFileSize(fileObj.size))

      const result = await smartCompress(fileObj)

      message.info(`压缩完成: ${result.compressionRatio.toFixed(1)}%`)

      file.file = result.file
    }

    file.url = URL.createObjectURL(file.file as File)
    file.status = 'finished'

  } catch (error) {
    console.error('处理失败:', error)
    file.status = 'error'
    message.error('处理失败')
  }
}
</script>

<style scoped>
.compression-test {
  padding: 20px;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}
</style>
